﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="RequestContext.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace RestClient
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Text;

    public class RequestContext
    {
        private readonly Dictionary<string, string> parameters = new Dictionary<string, string>();

        private readonly WebHeaderCollection headers = new WebHeaderCollection();

        public string Body { get; set; }

        public string Path { get; set; }

        public HttpMethod Method { get; set; }

        public string ContentType { get; set; }

        public void AddParameter(string name, string value)
        {
            this.parameters.Add(name, value != null ? Uri.EscapeDataString(value) : null);
        }

        public void AddHeader(string name, string value)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Header name must not be null or empty.", "name");
            }

            this.headers[name] = value;
        }

        public WebHeaderCollection GetHeaderCollection()
        {
            return new WebHeaderCollection { this.headers };
        }

        public string GetQueryString()
        {
            var stringBuilder = new StringBuilder();
            if (this.parameters.Any())
            {
                var first = this.parameters.First();
                stringBuilder.AppendFormat("?{0}={1}", first.Key, first.Value);

                if (this.parameters.Count > 1)
                {
                    var rest =
                        this.parameters.Skip(1)
                            .Select(parameter => string.Format("{0}={1}", parameter.Key, parameter.Value))
                            .Aggregate((currentParameters, next) => string.Format("{0}&{1}", currentParameters, next));

                    stringBuilder.AppendFormat("&{0}", rest);
                }
            }

            return stringBuilder.ToString();
        }

        public override string ToString()
        {
            return string.Format("{0}{1}", this.Path, this.GetQueryString());
        }
    }
}